package cn.wolfcode.crm.util;

import cn.wolfcode.crm.domain.Employee;
import cn.wolfcode.crm.domain.SystemLog;
import cn.wolfcode.crm.service.ISystemLogService;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.shiro.SecurityUtils;
import org.aspectj.lang.JoinPoint;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

/**
 * @program: crm
 * @description: 日志的切面
 * @author: Mr.chen
 * @create: 2018-07-15 14:45
 **/
@Component("logAspect")
public class SystemLogAspect {
    @Autowired
    private ISystemLogService systemLogService;

    public void write(JoinPoint jp) throws JsonProcessingException {

        System.out.println("--------------"+jp.getTarget());
        //日志插入的操作不要记录
        if (jp.getTarget() instanceof ISystemLogService) {
            return;
        }


        SystemLog log = new SystemLog();
        log.setOptime(new Date());
        log.setOpuser((Employee) SecurityUtils.getSubject().getPrincipal());

        //目标对象
        //System.out.println(jp.getTarget().getClass().getName());
        //目标方法
        //System.out.println(jp.getSignature().getName());
        //目标方法参数
        //System.out.println(jp.getArgs());

        //当前执行的方法
        log.setFunction(jp.getTarget().getClass().getName() + ":" + jp.getSignature().getName());
        //当前执行的参数, 将参数转换成Json对象
        log.setParams(new ObjectMapper().writeValueAsString(jp.getArgs()));

        //获取ip
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();
        log.setOpip(request.getRemoteAddr());


        systemLogService.save(log);


    }


}
